# encoding: utf-8
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.urlresolvers import reverse, reverse_lazy
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render, render_to_response, get_object_or_404
import codecs, sys

from django.views.generic import CreateView
from django.views.generic import DeleteView
from django.views.generic import DetailView
from django.views.generic import ListView
from django.views.generic import RedirectView
from django.views.generic import UpdateView

from article.forms import UserRegisterForm, ArticleAddForm, UserCreateForm

reload(sys)
sys.setdefaultencoding('utf-8')
from django.contrib.auth import logout
from article.models import Article, Sort
from django.template import RequestContext


# 用户注册
def user_register(request):
    form = UserRegisterForm()
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            # new_user = User.objects.create_user(request.POST['username'], '', request.POST['password'])

            user = User(username=request.POST['username'])
            user.set_password(request.POST['password'])
            user.save()

            return render(request, 'registration/reg_success.html')
        else:
            return render(request, 'registration/register.html', {'form': form})
    else:
        return render(request, 'registration/register.html', {'form': form})


class UserCreate(CreateView):
    template_name = 'registration/register.html'
    form_class = UserCreateForm

    def form_valid(self, form):
        # super(UserCreate, self).form_valid(form)
        user = form.save(commit=False)
        user.set_password(user.password)
        user.save()
        return render_to_response('registration/reg_success.html')



# 主页(文章列表页)
# 1.方法视图
def index(request):
    article_list = Article.objects.order_by('-id').all()
    paginator = Paginator(article_list, 5)  # 五条数据为一页
    page = request.GET.get('page')  # 获取页码
    try:
        article_all = paginator.page(page)  # 获取某页对应的记录
    except PageNotAnInteger:  # 如果页码不是整数
        article_all = paginator.page(1)  # 取第一页的数据
    except EmptyPage:  # 如果页码太大，没有对应的记录
        article_all = paginator.page(paginator.num_pages)  # 取最后一页的记录

    return render(request, 'index.html', {'article_all': article_all, 'title': '全部文章'})
    # 同等 return render_to_response('index.html',context_instance=RequestContext(request))




# 1.类视图
class ArticleList(ListView):
    # model = Article
    # 模板位置：/templates/article/article_list.html
    # 变量名：article_list
    paginate_by = 5
    # 一个页面显示五条数据
    template_name = 'index.html'
    # 手动设置模板位置
    context_object_name = 'article_all'
    # 手动设置变量名为article_all
    # queryset = Article.objects.all() 可使用queryset参数指定一个对象列表来替换model参数，两者等价
    queryset = Article.objects.order_by('-id').all()


# 文章详情
def article_see(request, id):
    article = Article.objects.get(pk=id)

    return render(request, 'details.html', {'article': article})


class ArticleDetail(DetailView):
    model = Article
    template_name = 'details.html'

    # def get_article(self, queryset=None): # 重写对象并封装调用
    #     article = super(ArticleDetail, self).get_object()
    #     article.last_accessed = timezone.now()  # 例如article有个最后访问时间字段(last_accessed)需要重写
    #     article.save()
    #     return article


# 分类查看
def sort_see(request, sort):
    article_sort = Article.objects.filter(sort__classifies__contains=sort)
    paginator = Paginator(article_sort, 5)  # 五条数据为一页
    page = request.GET.get('page')  # 获取页码
    try:
        article_all = paginator.page(page)  # 获取某页对应的记录
    except PageNotAnInteger:  # 如果页码不是整数
        article_all = paginator.page(1)  # 取第一页的数据
    except EmptyPage:  # 如果页码太大，没有对应的记录
        article_all = paginator.page(paginator.num_pages)  # 取最后一页的记录
    return render(request, 'index.html', {'article_all': article_all, 'title': sort + '类型的全部文章'})


class SortArticleList(ListView):
    template_name = 'index.html'
    context_object_name = 'article_all'
    paginate_by = 5

    # queryset = Article.objects.filter(sort__classifies__contains=' ')
    def get_queryset(self):  # 重写queryset
        self.sort = get_object_or_404(Sort, classifies=self.kwargs['sort'])  #也可用位置参数self.args[0]
        return Article.objects.filter(sort=self.sort)
        # return Article.objects.filter(sort__classifies=self.kwargs['sort'])

    def get_context_data(self, **kwargs):  # 传递额外的内容到模板页(sort)
        context = super(SortArticleList, self).get_context_data(**kwargs)
        context['title'] = self.sort
        return context

# 用户退出
def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('article:index'))

# 添加文章
#(forms.Form)
# @login_required(login_url='/login/')
# def article_add(request):
#     form = ArticleAddForm()
#     if request.method == 'POST':
#         form = ArticleAddForm(request.POST, request.FILES)
#         if form.is_valid():
#             article = Article()
#             article.title = form.cleaned_data['title']
#             article.cover_img = request.FILES['cover_img']
#             article.content = form.cleaned_data['content']
#             article.author = request.user
#             article.last_editor = request.user
#             article.sort = form.cleaned_data['sort']
#             article.save()
#
#             return HttpResponseRedirect(reverse('article:index'))
#         else:
#             return render_to_response('article_add.html',
#                                       context_instance=RequestContext(request, {'form': form, 'title': '添加文章'}))
#     return render(request, 'article_add.html', {'form': form, 'title': '添加文章'})

#(forms.ModelForm)
@login_required
def article_add(request):
    form = ArticleAddForm()
    if request.method == 'POST':
        form = ArticleAddForm(request.POST, request.FILES)
        if form.is_valid():
            article = form.save(commit=False)
            article.author = request.user
            article.last_editor = request.user
            article.save()

            return HttpResponseRedirect(reverse('article:index'))
        else:
            return render_to_response('article_add.html',
                                      context_instance=RequestContext(request, {'form': form, 'title': '添加文章'}))
    return render(request, 'article_add.html', {'form': form, 'title': '添加文章'})

class ArticleCreate(CreateView):
    template_name = 'article_add.html'
    form_class = ArticleAddForm
    # success_url = '/article/'

    def form_valid(self, form):
        form.instance.author = self.request.user
        form.instance.last_editor = self.request.user
        return super(ArticleCreate,self).form_valid(form)

    def get_success_url(self):
        return reverse('article:index')

# 文章管理
@login_required
def article_manage(request):
    if request.user.is_superuser:
        my_articles = Article.objects.all()
    else:
        my_articles = Article.objects.filter(author=request.user)
    paginator = Paginator(my_articles, 5)
    page = request.GET.get('page')
    try:
        article_all = paginator.page(page)
    except PageNotAnInteger:
        article_all = paginator.page(1)
    except EmptyPage:
        article_all = paginator.page(paginator.num_pages)
    return render(request, 'index.html', {'article_all': article_all, 'title': '我的管理'})

class ArticleManage(ArticleList):
    template_name = 'index.html'
    context_object_name = 'article_all'
    paginate_by = 5

    def get_queryset(self):  # 重写queryset
        return Article.objects.filter(author=self.request.user)



# 文章编辑
# def article_edit(request, id):
#     article_content = Article.objects.get(pk=id)
#     form = ArticleAddForm()
#     if request.method == 'POST':
#         form = ArticleAddForm(request.POST, request.FILES)
#         if form.is_valid():
#             article = article_content
#             article.title = form.cleaned_data['title']
#             article.cover_img = request.FILES['cover_img']
#             article.content = form.cleaned_data['content']
#             article.last_editor = request.user
#             article.sort = form.cleaned_data['sort']
#             article.save()
#             return HttpResponseRedirect(reverse('article:my_admin'))
#         else:
#             return render(request, 'article_add.html', {'article_old': article_content, 'form': form, 'title': '文章编辑'})
#     return render(request, 'article_add.html', {'article_old': article_content, 'form': form, 'title': '文章编辑'})

def article_edit(request, id):
    article_content = Article.objects.get(pk=id)
    form = ArticleAddForm(instance=article_content)
    if request.method == 'POST':
        form = ArticleAddForm(request.POST, request.FILES, instance=article_content)
        if form.is_valid():
            article = form.save(commit=False)
            article.last_editor = request.user
            article.save()
            return HttpResponseRedirect(reverse('article:my_admin'))
        else:
            return render(request, 'article_add.html', {'article_old': article_content, 'form': form, 'title': '文章编辑'})
    return render(request, 'article_add.html', {'article_old': article_content, 'form': form, 'title': '文章编辑'})


class ArticleUpdate(UpdateView):
    template_name = 'article_add.html'
    form_class = ArticleAddForm
    success_url = reverse_lazy('article:index')
    def get_queryset(self):
        user = self.request.user
        queryset = Article.objects.all()
        if not user.is_superuser:
            return queryset.filter(author=self.request.user)
        return queryset

    # self.get_object()


    def form_valid(self, form):
        form.instance.last_editor = self.request.user
        return super(ArticleUpdate,self).form_valid(form)


# 文章删除
def article_del(request, id):
    article = Article.objects.get(pk=id)
    article.delete()
    return HttpResponseRedirect(reverse('article:index'))

class ArticleDelete(DeleteView):
    model = Article
    template_name = 'article_del.html'
    success_url = reverse_lazy('article:index')

